require([
  'jquery',
  'pageInit',
  'dataTableFilter',
  'loading',
  'dateRange',
  'moment',
  'listAsyncOp',
  'amcharts',
  'amcharts.serial'
], function($, vamakerPage, VamDataTable, VamLoader, DateRange, moment, VamListOp) {
  $(function () {
    var $rangeDateBtn = $('#range-date-btn'),
      $rangeDate = $('#range-date'),
      dateRange = new DateRange(),
      selectDate;
    dateRange.dateRange($rangeDate, {
      maxDate: moment(),
      ranges: {
        'Today': [moment(), moment()],
        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
        'Last 7 Days': [moment().subtract(6, 'days'), moment()],
        'Last 30 Days': [moment().subtract(29, 'days'), moment()],
        'This Month': [moment().startOf('month'), moment().endOf('month')],
        'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
      }
    });
  });
  // Filer Select.
  $(function () {
    var campaignToLauch = $.parseJSON(VAM.getVar('CAMPAIGN_TO_LAUNCH')),
    launchToStrategy = $.parseJSON(VAM.getVar('LAUNCH_TO_STRATEGY')),
    strategyToCreative = $.parseJSON(VAM.getVar('STRATEGY_TO_CREATIVE')),
    $filterSelect = $('#filter-frm').find('.form-control').filter('select'),
    $filterMarket = $('#filter_market'),
    $filterCampaign = $('#filter_campaign'),
    $filterLaunch = $('#filter_launch'),
    $filterStrategy = $('#filter_strategy'),
    $filterCreative = $('#filter_creative'),
    selectChangeFun, selectChangeFun2, 
    selectResetFun, marketValue;
    // console.log(marketToCampaign);
    // console.log(campaignToLauch);
    // console.log(launchToStrategy);
    // console.log(strategyToCreative); 
    selectResetFun = function (num) {
      var start = parseInt(num, 10);
      for (var i = start, len =  $filterSelect.length; i < len; i++) {
        $filterSelect.eq(i).children(':gt(0)').remove();
      };
    };
    selectChangeFun = function ($master, $slave, dataMaster) {
      // console.log($master);
      // console.log($slave);
      // console.log(dataMaster);
      $master.on('change',function(){
        var $me = $(this),
          meVal = $me.find('option:selected').text(),
          dataSlaveObj = dataMaster[meVal] ? dataMaster[meVal]: {id: "null","value": []},
          dataSlave = dataSlaveObj.value,
          number = parseInt($me.data('number'), 10),
          i,j;
          marketValue = meVal;
        // console.log(meVal);
        // console.log(dataSlaveObj);
        // console.log(dataSlave);
        $slave.children(':gt(0)').remove();
        // $slave.append('<option value="all">全部</option>');
        for (i=0, j=dataSlave.length; i<j; i++) {
          var item = dataSlave[i];
          $slave.append('<option value="' + item.id + '">' +item.value +'</option>');
        };
        selectResetFun(number + 1);
      });
    };
    selectChangeFun2 = function ($master, $slave, dataMaster) {
      $master.on('change',function(){
        var $me = $(this),
          meVal = $me.find('option:selected').text(),
          dataSlaveObj = dataMaster[marketValue][meVal] ? dataMaster[marketValue][meVal]: {id: "null","value": []},
          dataSlave = dataSlaveObj.value,
          number = parseInt($me.data('number'), 10),
          i,j;
   
        $slave.children(':gt(0)').remove();
        for (i=0, j=dataSlave.length; i<j; i++) {
          var item = dataSlave[i];
          $slave.append('<option value="' + item.id + '">' +item.value +'</option>');
        };
        selectResetFun(number + 1);
      });
    };
    for(var key in campaignToLauch){
      var object = campaignToLauch[key];
      // console.log(key);
      if(campaignToLauch.hasOwnProperty(key)) {
        $filterCampaign.append('<option value="' + object.id + '">' + key + '</option>');
      }
    };
    // selectChangeFun($filterMarket, $filterCampaign, marketToCampaign);
    selectChangeFun($filterCampaign, $filterLaunch, campaignToLauch);
    // selectChangeFun2($filterCampaign, $filterLaunch, campaignToLauch);
    selectChangeFun2($filterLaunch, $filterStrategy, launchToStrategy);
    selectChangeFun2($filterStrategy, $filterCreative, strategyToCreative);
    // $filterMarket.trigger('change');
    $filterCampaign.trigger('change');
  });
  $(function () {
    var $chartDataHolder = $('#summary-report-data'),
     appColors = VAM.getVar("VAM_PARAMS").colors,
     filterStatus = VAM.getVar('FILTER_STATUS'),
     units1 = '',
     units2 = '',
     chartDataHolder;

    var
      chartGraph = [
        {
          "id": "g1",
          "valueAxis": "v1",
          "lineColor": appColors[0],
          "fillColors": appColors[0],
          "fillAlphas": 1,
          "lineAlpha": 1,
          "type": "column",
          "title": VAM.j('Cost'),
          "valueField": "y0",
          "clustered": false,
          "columnWidth": 0.3,
          "legendValueText": "[[value]]",
          "animationPlayed": true,
          "balloonFunction": function (item) {
            return VAM.j('Cost') + "<br/><b style='color: " + appColors[0] + "'>●</b><b> " + item["dataContext"]["y0"] + " " + units1 + "</b>";
          }
        },
        {
          "id": "g3",
          "valueAxis": "v1",
          "bullet": "round",
          "bulletBorderAlpha": 1,
          "bulletColor": "#FFFFFF",
          "bulletSize": 6,
          "hideBulletsCount": 50,
          "lineThickness": 2,
          "lineColor": appColors[2],
          "type": "line",
          "title": VAM.j('Click'),
          "useLineColorForBulletBorder": true,
          "valueField": "y2",
          "animationPlayed": true,
          "balloonText": "[[title]]<br/><b style='color: " + appColors[2] + "'>●</b><b> [[value]]</b>"
        },
        {
          "id": "g6",
          "valueAxis": "v4",
          "bullet": "diamond",
          "bulletBorderAlpha": 1,
          "bulletColor": "#FFFFFF",
          "bulletSize": 6,
          "hideBulletsCount": 50,
          "lineThickness": 2,
          "lineColor": appColors[5],
          "type": "line",
          "title": 'CPC',
          "useLineColorForBulletBorder": true,
          "valueField": "y5",
          "animationPlayed": true,
          "balloonText": "[[title]]<br/><b style='color: " + appColors[5] + "'>●</b><b> [[value]]</b>"
        }
      ];

    if (filterStatus) {
      chartGraph.push({
        "id": "g2",
        "valueAxis": "v2",
        "bullet": "square",
        "bulletBorderAlpha": 1,
        "bulletColor": "#FFFFFF",
        "bulletSize": 6,
        "hideBulletsCount": 50,
        "lineThickness": 1,
        "lineColor": appColors[1],
        "type": "line",
        "title": VAM.j('Show'),
        "useLineColorForBulletBorder": true,
        "valueField": "y1",
        "animationPlayed": true,
        "balloonFunction": function (item) {
          return VAM.j('Show') + "<br/><b style='color: " + appColors[1] + "'>●</b><b> " + item["dataContext"]["y1"] + " " + units2 + "</b>";
        }
      });
      chartGraph.push({
        "id": "g4",
        "valueAxis": "v3",
        "bullet": "triangleUp",
        "bulletBorderAlpha": 1,
        "bulletColor": "#FFFFFF",
        "bulletSize": 6,
        "hideBulletsCount": 50,
        "lineThickness": 2,
        "lineColor": appColors[3],
        "type": "line",
        "title": VAM.j('Click Rate'),
        "useLineColorForBulletBorder": true,
        "valueField": "y3",
        "animationPlayed": true,
        "balloonText": "[[title]]<br/><b style='color: " + appColors[3] + "'>●</b><b> [[value]]%</b>"
      });
    }

    chartDataHolder = AmCharts.makeChart("summary-report-data", {
      "type": "serial",
      "fontFamily": '"Helvetica Neue",Helvetica,"Hiragino Sans GB","Segoe UI","Microsoft Yahei",Tahoma,Arial,STHeiti,sans-serif',
      "fontSize": 13,
      "startDuration": 1,
      "creditsPosition": "top-right",
      "dataDateFormat": "YYYY/MM/DD",
      "valueAxes": [
        {
          "id": "v1",
          "title": VAM.j('Cost') + '(' + VAM.j('￥') + ')' + ' / ' + VAM.j('Click'),
          "position": "left",
          "autoGridCount": true
        },
        // {
        //   "id": "v2",
        //   "title": VAM.j('Show'),
        //   "gridAlpha": 0,
        //   "position": "left",
        //   "autoGridCount": true,
        //   "labelOffset": 80
        // },
        // {
        //   "id": "v3",
        //   "title": VAM.j('Ratio(%)'),
        //   "gridAlpha": 0,
        //   "position": "right",
        //   "autoGridCount": true
        // },
        {
          "id": "v4",
          "title": 'CPC',
          "gridAlpha": 0,
          "position": "right",
          "autoGridCount": true
          // "labelOffset": 80
        }
      ],
      "graphs": chartGraph,
      "chartCursor": {
        "pan": false,
        "cursorColor": appColors[1],
        "valueLineEnabled": false,
        "valueLineBalloonEnabled": false,
        "cursorAlpha": 0,
        "valueLineAlpha": 0.5
      },
      "categoryField": "x",
      "categoryAxis": {
        "gridAlpha": 0,
        "dashLength": 1,
        "labelRotation": 15,
        "minorGridEnabled": true
      },
      "legend": {
        "useGraphSettings": true,
        "valueAlign": "left",
        "align": "center",
        "valueWidth": 80
      },
      "balloon": {
        "borderThickness": 1,
        "shadowAlpha": 0
      },
      "dataProvider": [{
        x: "-/-",
        y0: 0.00,
        y1: 0,
        y2: 0,
        y3: 0.00,
        y4: 0.00,
        y5: 0.00
      }]
    });

    // Data table.
    var 
      $dataTable = $('#data-table'),
      $tableTotal = $('.table-total'),
      $filterFrm = $('#filter-frm'),
      $submitBtn = $filterFrm.find('button[type="submit"]'),
      dataUrl = VAM.getVar('REPORT_DATA_LIST'),
      dataPackInfoUrl = VAM.getVar('REPORT_PACK_INFO_DATA_LIST'),
      fitlerStatus = VAM.getVar('FILTER_STATUS'),
      $reportDataThead = $dataTable.find('thead'),
      $loadingWrap = new VamLoader().loader($('#list-loading-wrap')),
    listTable, tableOptions = {},
    totalDataRender, graphDataRender, packInfoListRender;

    // console.log(graphDataHolder);
    totalDataRender = function (data) {
      var result = '', costFilterStatus = VAM.getVar('COST_FILTER_STATUS');
      if (costFilterStatus) {
        result = '<td><p class="text-success" title="' + data[0][0] + '"><i class="fa fa-rmb"></i> ' + data[0][0] + '</p>'
               + '<p class="text-success" title="' + data[0][0] + '"><i class="fa fa-rmb"></i> ' + data[0][1] + '</p></td>'
              //  + '<td title="' + data[1] + '">' + data[1] + '</td>'
               + '<td title="' + data[2] + '">' + data[2] + '</td>'
              //  + '<td title="' + data[3] + '">' + data[3] + ' %</td>'
              //  + '<td><p class="text-success" title="' + data[4][0] + '"><i class="fa fa-rmb"></i> ' + data[4][0] + '</p>'
              //  + '<p class="text-success" title="' + data[4][1] + '"><i class="fa fa-rmb"></i> ' + data[4][1] + '</p></td>'
               + '<td><p class="text-success" title="' + data[5][0] + '"><i class="fa fa-rmb"></i> ' + data[5][0] + '</p>'
               + '<p class="text-success" title="' + data[5][1] + '"><i class="fa fa-rmb"></i> ' + data[5][1] + '</p></td>';
      } else {
        result = '<td><p class="text-success" title="' + data[0] + '"><i class="fa fa-rmb"></i> ' + data[0] + '</p></td>'
              //  + '<td title="' + data[1] + '">' + data[1] + '</td>'
               + '<td title="' + data[2] + '">' + data[2] + '</td>'
              //  + '<td title="' + data[3] + '">' + data[3] + ' %</td>'
              //  + '<td><p class="text-success" title="' + data[4] + '"><i class="fa fa-rmb"></i> ' + data[4] + '</p></td>'
               + '<td><p class="text-success" title="' + data[5] + '"><i class="fa fa-rmb"></i> ' + data[5] + '</p></td>';
      };
       return result;
    };
    graphDataRender = function (data) {
      // console.log(data);
      chartDataHolder.dataProvider = data;
      chartDataHolder.validateNow();
      chartDataHolder.validateData();
    }
    packInfoListRender = function (data) {
      // console.log(data)
      var resultStr = '',
        subArr = data;
      if (subArr.length === 0) {
        resultStr = '<tr><td colspan="2"><p class="text-center">' + VAM.j('The data in the table is empty') + '</p></td></tr>';
      } else {
        for (var i = 0; i < subArr.length; i++) {
          var subStr = '<tr>'
                    //  + '<td><p title="' + subArr[i].id + '">' + subArr[i].id +'</p></td>'
                     + '<td><p title="' + subArr[i].name + '">' + subArr[i].name +'</td>'
                     + '<td><p title="' + subArr[i].cost + '">' + subArr[i].cost +'</td>'
                     + '<td><p title="' + subArr[i].showCount + '">' + subArr[i].showCount +'</td>'
                     + '<td><p title="' + subArr[i].clickCount + '">' + subArr[i].clickCount +'</td>'
                     + '<td><p title="' + subArr[i].clickRate + '">' + subArr[i].clickRate +'</td>'
                     + '<td><p title="' + subArr[i].cpm + '">' + subArr[i].cpm +'</td>'
                     + '<td><p title="' + subArr[i].cpc + '">' + subArr[i].cpc +'</td>'
                     + '</tr>';
          resultStr += subStr;
        }
      };
      resultStr = '<table cellpadding="0" cellspacing="0" border="0" class="table table-hover table-bordered" style="margin-bottom:0;border: 1px solid #ddd;">'
                + '<thead>'
                + '<tr>'
                // + '<th title="ID">ID</th>'
                + '<th title="' + VAM.j('App Name') + '">' + VAM.j('App Name') + '</th>'
                + '<th title="' + VAM.j('Cost') + '">' + VAM.j('Cost') + '</th>'
                + '<th title="' + VAM.j('Shows') + '">' + VAM.j('Shows') + '</th>'
                + '<th title="' + VAM.j('Clicks') + '">' + VAM.j('Clicks') + '</th>'
                + '<th title="' + VAM.j('Click Rate(%)') + '">' + VAM.j('Click Rate(%)') + '</th>'
                + '<th title="CPM">CPM</th>'
                + '<th title="CPC">CPC</th></tr>'
                + '</thead>'
                + '<tbody>'
                + resultStr
                + '</tbody></table>';
      return resultStr;
    };
    // Table settings.
    tableOptions = {
      'ajax': {
        'type': 'post',
        'url': dataUrl
      },
      'order': [0,'desc'],
      'columns': [
        {'data': 'date'},
        {'data': 'id'},
        // {'data': 'media'},
        // {'data': 'market'},
        {'data': 'solutionName'},
        {'data': 'creativeName'},
        {'data': 'pack'},
        // {'data': 'channel'},
        // {'data': 'originCost'},
        {'data': 'cost'},
        // {'data': 'reqCount'},
        // {'data': 'bidCount'},
        // {'data': 'showCount'},
        {'data': 'clickCount'},
        // {'data': 'clickRate'},
        // {'data': 'cpm'},
        {'data': 'cpc'}
        // ,
        // {'data': 'convertRate'},
        // {'data': 'convertNum'}
      ],
      'columnDefs': [
        {
          'targets': [0,1,2,3,5,6],
          'render': function (data, type, full, meta) {
              return '<p title="' + data + '">' + data + '</p>';
          }
        },
        {
          'targets': 4,
          'render': function (data, type, full, meta) {
            return '<p title="' + data + '">' + data
              + '<button title="' + VAM.j('View Pack Infos') + '" class="btn btn-link btn-xs pull-right tab-pack-list" data-type="pack" data-date="' + full.date + '" data-launch="' + full.launchId + '" data-strategy="' + full.solutionId + '" data-creative="' + full.creativeId + '" data-pack="' + full.packId + '" data-loading-text="<i class=\'fa fa-spinner fa-spin\'></i> ' + VAM.j('loading') + '..." data-id="' + full.id + '"><i class="fa fa-plus-circle"></i></button>'
              + '</p>'
          }
        },
        // {
        //   'targets': -3,
        //   'render': function (data, type, full, meta) {
        //     return '<p class="text-default" title="' + data + '">' + data + ' %</p>';
        //   }
        // },
        {
          'targets': [2, 3],
          'visible': fitlerStatus
        },
        {
          'targets': [-1],
          'render': function (data, type, full, meta) {
            return '<p class="text-success" title="' + data + '"><i class="fa fa-rmb"></i> ' + data + '</p>';
          }
        },
        // {
        //   'targets': [2,3,5,6],
        //   'visible': VAM.getVar('COST_FILTER_STATUS'),
        //   'orderable': false,
        //   'render': function (data, type, full, meta) {
        //     var check = data === "open" ? "checked" : "",
        //       resultStr;
        //     resultStr = '<p title="' + data + '">' + data +'</p>';
        //     return resultStr;
        //   }
        // }
      ],
      'vamSettings': {
        'vamColumnFilter': false,
      },
      'initComplete': function() {
        tableResize = new VamDataTable().columnResize($dataTable);
      },
    };
    $dataTable
    .on('preXhr.dt', function(evt) {
      $loadingWrap.show();
      $submitBtn.button('loading');
    });
    listTable = new VamDataTable().dataTables($dataTable, tableOptions);
    // After table data list.
    listTable.on('xhr.dt', function(evt, settings, json) {
      $submitBtn.button('reset');
      $tableTotal.find('.total-data').html(totalDataRender(json['total']));
      graphDataRender(json['graph']);
      $loadingWrap.fadeOut();
    });

    $dataTable.on('click', 'tbody td .tab-pack-list', function () {
      var $me = $(this),
          opDate = $me.data('date'),
          opLaunchId = $me.data('launch'),
          opStrategyId = $me.data('strategy'),
          opCreativeId = $me.data('creative'),
          opPackId = $me.data('pack'),
          opType = $me.data('type'),
          $icon = $me.find('.fa'),
          tr = $(this).parents('tr'),
          row = listTable.row(tr);
      $icon.toggleClass('fa-minus-circle');
      if (row.child.isShown()) {
        row.child.hide();
        tr.removeClass('shown');
      } else {
        VamListOp.listOp({
          url: dataPackInfoUrl,
          data: {
            launch: opLaunchId,
            strategy: opStrategyId,
            creative: opCreativeId,
            pack: opPackId,
            range_date: opDate,
            type: opType
          },
          before: function () {
            $me.button('loading');
          },
          success: function (data) {
            row.child(packInfoListRender(data)).show();
            tr.addClass('shown');
          },
          always: function () {
            $me.button('reset');
          }
        });
      }
    });

    $filterFrm.submit(function (evt) {
      var $me = $(this),
        filterTxt = $me.serialize(),
        $reportDownload = $('#report_download'),
        exportUrl = VAM.getVar('EXPORT_REPORT_DATA');
      evt.preventDefault();
      filterTxt = filterTxt ? '?' + filterTxt : '';
      // console.log(filterTxt);
      exportUrl = exportUrl + filterTxt;
      listTable.ajax.url(dataUrl + filterTxt).load();
      $reportDownload.prop('href', exportUrl);
      return false;
    });
  });
});
